package com.mychat.controller;

import com.mychat.annotation.GlobalInterceptor;
import com.mychat.entity.Constants;
import com.mychat.entity.config.AppConfig;
import com.mychat.entity.dto.MessageSendDto;
import com.mychat.entity.dto.TokenUserInfoDto;
import com.mychat.entity.po.ChatMessage;
import com.mychat.entity.vo.ResponseVO;
import com.mychat.enums.MessageTypeEnum;
import com.mychat.enums.ResponseCodeEnum;
import com.mychat.exception.BusinessException;
import com.mychat.service.ChatMessageService;
import com.mychat.service.ChatSessionUserService;
import com.mychat.utils.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

@RestController
@RequestMapping("/chat")
public class ChatController extends ABaseController{
    private static final Logger logger = LoggerFactory.getLogger(ChatController.class);

    @Resource
    private ChatMessageService chatMessageService;

    @Resource
    private ChatSessionUserService chatSessionUserService;

    @Resource
    private AppConfig appConfig;

    @RequestMapping("/sendMessage")
    @GlobalInterceptor
    public ResponseVO sendMessage(HttpServletRequest request, @NotEmpty String contactId, @NotEmpty @Max(500) String messageContent, @NotNull Integer messageType, Long fileSize, String fileName, Integer fileType) throws BusinessException {
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfo(request);
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setContactId(contactId);
        chatMessage.setMessageContent(messageContent);
        chatMessage.setFileSize(fileSize);
        chatMessage.setFileName(fileName);
        chatMessage.setFileType(fileType);
        chatMessage.setMessageType(messageType);
        MessageSendDto messageSendDto = chatMessageService.saveMessage(chatMessage, tokenUserInfoDto);
        return getSuccessResponseVO(messageSendDto);
    }

    @RequestMapping("/uploadFile")
    @GlobalInterceptor
    public ResponseVO uploadFile(HttpServletRequest request, @NotNull Long messageId, @NotNull MultipartFile file, @NotNull MultipartFile cover) throws BusinessException {
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfo(request);

        chatMessageService.saveMessageFile(tokenUserInfoDto.getUserId(), messageId, file, cover);
        return getSuccessResponseVO(null);
    }

    @RequestMapping("/downloadFile")
    @GlobalInterceptor
    public void downloadFile(HttpServletRequest request, HttpServletResponse response, @NotNull String fileId, @NotNull Boolean showCover) throws BusinessException {
        TokenUserInfoDto tokenUserInfoDto = getTokenUserInfo(request);
        FileInputStream in = null;
        OutputStream out = null;
        try {
            File file = null;
            if(!StringUtils.isNumber(fileId)) {
                String avatarFolderName = Constants.FILE_FOLDER_FILE + Constants.FILE_FOLDER_AVATAR_NAME;
                String avatarPath = appConfig.getProjectFolder() + avatarFolderName + fileId;
                if(showCover) {
                    avatarPath = avatarPath + Constants.COVER_IMAGE_SUFFIX;
                } else {
                    avatarPath = avatarPath + Constants.IMAGE_SUFFIX;
                }
                file = new File(avatarPath);
                if(!file.exists()) {
                    throw new BusinessException(ResponseCodeEnum.CODE_602);
                }
                response.setContentType("application/x-msdownload;charset=UTF-8");
                response.setHeader("Content-Disposition", "attachment;");
                response.setContentLengthLong(file.length());
                in = new FileInputStream(file);
                byte[] byteData = new byte[1024];
                out = response.getOutputStream();
                int len;
                while((len = in.read(byteData)) != -1) {
                    out.write(byteData, 0, len);
                }
                out.flush();
            } else {
                file = chatMessageService.downloadFile(tokenUserInfoDto, Long.parseLong(fileId), showCover);
            }
        } catch (Exception e) {
            logger.error("下载文件失败", e);
        } finally {
            if(out != null) {
                try {
                    out.close();
                } catch (Exception e) {
                    logger.error("关闭输出流失败", e);
                }
            }
            if(in != null) {
                try {
                    in.close();
                } catch (Exception e) {
                    logger.error("关闭输出流失败", e);
                }
            }
        }
    }
}
